<?php
namespace Wx\Controller;
use Think\Controller;
use Wx\Model\ShopPayLogModel;

class PayLogController extends Controller{
    //扫码进入这个页面，用户在该页面输入支付金额
    public function Index(){
        $sn = I('sn');  //接收二维码传递过来的参数，格式123(店铺id)-4567(店铺老板id)
        if ($sn){
            $store_id = strstr($sn,"-",true);
			
			//自动绑定二维码
			$id_str=explode('-',$sn);//dump($id_str);
			/*
			*$id_str[0]店铺id
			*$id_str[1]用户id
			*/
			$shop_pay=D('shop_pay');
			$member=D('member');
			
			$getone=$shop_pay->where("s_id=".$id_str[0]." and u_id=".$id_str[1])->find();
			if($getone['binding']==0){
				//该二维码未绑定用户
				if(session('openid')!=''){
					//该用户是门店，提醒不要重复绑定 
					$getinfo=$member->where("`openid` LIKE '".session('openid')."'")->find();
					if($getinfo['u_type']==1){
						$this->error('请不要重复绑定二维码！','/Wx/Index');
					}
					//第一，删除自动生成的用户条目
					$member->where("`openid` LIKE '".session('openid')."'")->setField('openid','0000000000');
					//第二，把openid更新到该二维码绑定的用户id中
					$alt0=$member-> where('id='.$id_str[1])->setField('openid',session('openid'));
					$alt1=$shop_pay-> where('id='.$getone['id'])->setField('binding',1);
					if($alt0>0 and $alt1>0)$this->success('恭喜您！二维码绑定成功', '/Wx/Index');
					session(null); // 清空当前的session
				}else{
					//提醒要关注并且登录后再来绑定
					$this->error('绑定二维码失败，请关注登录后扫码绑定！','/Wx/Index');
				}//end if
			}else{
			}
			//自动绑定二维码-end
			//确定微信扫码的用户获取积分
			$path =  $_SERVER['REQUEST_URI'];//dump($path);
			$model = new ShopPayLogModel();
			$isWxOrAlipay = $model->isWxOrAlipay();
			if($isWxOrAlipay == 'wxpay' ){
				//echo "微信打开";
				//跳转到微信授权
				//dump(session('openid'));
				if(session('openid')=='')redirect('/Wx/Auth/index?path='.$path);
			}else if($isWxOrAlipay == 'alipay'){
				//echo "支付宝打开";
			}else{
				$this->error('请使用微信或者支付宝扫码打开！');
			}
			//确定微信扫码的用户获取积分-end
            $storeInfo = M('shop_store')->where(array('id'=>$store_id))->field('id,storename,u_id')->find(); //查询店铺名称
            $this->assign('storeInfo',$storeInfo);
            $this->display();
        }else{
            $this->error('缺少参数，请检查');
        }//end if $sn
    }//end fun Index()
    // 用户输入支付金额-调用支付接口
    public function toPay(){
        if(IS_POST){
            $post = I('post.');
            $model = new ShopPayLogModel();
            // 调用支付接口
            $result = $model->pay($post);
        }else{
            $this->error('非法进入');
        }//end if IS_POST
    }//end fun toPay()
    // 用于接收异步通知
    public function notifyPay() {
        $res = file_get_contents('php://input');
        $Arr = array();
        $res = explode('&', $res);
        foreach($res as $v) {
            $value = explode('=', $v);
            $Arr[$value[0]] = urldecode($value[1]);
        }
        $model = new ShopPayLogModel();
        $key = C('IPAY_NOW.appKey');            //商户密钥
        $signatrue = $model->getSignTrue($Arr, $key);
        if($signatrue == $Arr['signature']) {
            //异步通知验签通过，在此处写业务逻辑
            $pay_info = M('shop_pay_log')->where(array('pay_sn'=>$Arr['mhtOrderNo'],'status'=>0))->find();
            if($pay_info){
                if($pay_info['consumer_id']!=''){//微信用户支付，增加积分
                    M('member')->where(array('openid'=>$pay_info['consumer_id']))->setInc('credit1',ceil($pay_info['amount']));
                    // 查询收款用户id
                    $u_id = M('member')->where(array('openid'=>$pay_info['consumer_id']))->getField('id');
                    changeCredit($u_id,'线下支付','credit1','+',ceil($pay_info['amount']));   //增加积分变动记录
                    //发送系统消息
                    sendVoice($u_id,'线下支付成功！增加积分'.ceil($pay_info['amount']));
                }
                // 更新支付状态
                $pay_info['status'] = 1;
                $pay_info['updated_at'] = time();
                M('shop_pay_log')->save($pay_info);
                // 店铺老板余额增加、增加余额变动记录
                M('member')->where('id = '.$pay_info['u_id'])->setInc('credit3',$pay_info['amount']);
                $result = changeCredit($pay_info['u_id'],'线下扫码支付','credit3','+',$pay_info['amount']);
                // 给店铺老板推送消息
                $send = sendMsg($pay_info['id']);
                echo 'success=Y';
            }
        } else {
            //异步通知验签失败，在此处写业务逻辑
            return null;
        }
    }//end fun notifyPay();
}//end class